package sync

import (
	"context"
	"gitee.com/hexug/go-tools/k8s"
	"gitee.com/hexug/go-tools/logger"
	"gitee.com/hexug/kube-sync/worker/sync"
	"github.com/spf13/cobra"
	"k8s.io/client-go/kubernetes"
)

var (
	ctx = context.Background()

	skipConfigMap bool
	skipPvPvc     bool
	skipSecret    bool
	namespaces    []string
	excludes      []string
	includes      []string

	kubeConfig string
	outPath    string

	Cmd = &cobra.Command{
		Use:     "sync",
		Short:   "同步 kubernetes 资源",
		Long:    "同步 kubernetes 资源",
		Example: "kube-sync sync -n <namespace> -d",
		Run: func(cmd *cobra.Command, args []string) {

			var k8sClient *kubernetes.Clientset
			if kubeConfig != "" {
				kct, _, err := k8s.GetClientSetFromKubeConfig(kubeConfig)
				if err != nil {
					logger.L().Fatalw("from kubeconfig get k8s client err", "err", err)
				}
				k8sClient = kct
			} else {
				kct, _, err := k8s.GetClientSet()
				if err != nil {
					logger.L().Fatalw("get k8s client err", "err", err)
				}
				k8sClient = kct
			}

			// 实际工作部分
			// 开始运行
			wk := sync.NewWorkloadSyncer(ctx, namespaces, excludes, includes, outPath, k8sClient, skipConfigMap, skipPvPvc, skipSecret)
			wk.Run()
		},
	}
)

func init() {
	Cmd.Flags().BoolVarP(&skipConfigMap, "skip-configmap", "c", false, "是否跳过configmap")
	Cmd.Flags().BoolVarP(&skipPvPvc, "skip-pv-pvc", "p", false, "是否跳过pv-pvc")
	Cmd.Flags().BoolVarP(&skipSecret, "skip-secret", "s", false, "是否跳过secret")

	Cmd.Flags().StringArrayVarP(&namespaces, "namespaces", "n", []string{}, "指定命名空间")
	Cmd.Flags().StringArrayVarP(&excludes, "excludes", "e", []string{}, "指定需要排除的服务 excludes和includes只能二选一  格式 <namespace>:<workload KIND>:<workload Name>")
	Cmd.Flags().StringArrayVarP(&includes, "includes", "i", []string{}, "指定需要包含的服务 excludes和includes只能二选一  格式 <namespace>:<workload KIND>:<workload Name>")
	Cmd.Flags().StringVarP(&outPath, "out", "o", "./", "指定输出路径")
	Cmd.Flags().StringVarP(&kubeConfig, "kube-config", "k", "", "指定kube-config文件")
}
